package com.yang.sso.oauth2.service.oidc;

import com.yang.sso.oauth2.mapper.UserMapper;
import com.yang.sso.oauth2.model.CustomOidcUserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.yang.common.core.enums.UserStatusEnum;
import org.yang.common.core.model.UserInfo;

import java.util.*;

/**
 * 自定义 OIDC 用户信息服务
 *
 * @author: lslands
 * @description:
 * @version：v1.0
 * @date: 2024/6/3 15:59
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomOidcUserInfoService {

    private final UserMapper userMapper;

    public CustomOidcUserInfo loadUserByUsername(String username) {
        UserInfo userInfo = null;
        try {
            userInfo = Optional.ofNullable(userMapper.selectUserInfo(username))
                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            Set<String> permssions = Optional.ofNullable(userMapper.selectAuthorizeByRoleId(userInfo.getRoles()))
                    .orElse(new HashSet<>());
            userInfo.setAuthorities(permssions);
            return new CustomOidcUserInfo(createUser(userInfo));
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return null;
        }
    }

    private Map<String, Object> createUser(UserInfo userInfo) {
        return CustomOidcUserInfo.customBuilder()
                .username(userInfo.getUsername())
                .nickname(userInfo.getNickname())
                .status(userInfo.getEnabled())
                .phoneNumber("15928310871")
                .email("1430536748@qq.com")
                .profile("https://www.qq.com")
                .build()
                .getClaims();
    }


}
